/**
 * Hr复核详细-提交审批
 */

import React, { useState, useMemo, useEffect, useRef } from 'react';
import { Form, Input, Spin, Row, Col, message } from 'antd';
import { useMeasure, useMount } from 'react-use';
import classNames from 'classnames';
import keyBy from 'lodash/keyBy';
import { withRouter } from 'umi';

import If from '@/components/If';
import DateFormatter from '@/components/DateFormatter';
import { isSuccess } from '@/utils/request';
import { numberFormat } from '@/utils/formatterUtil';
import { hrOverviewRecheck, querySalaryPayrollProcessRecordById } from '@/services/salaryManage/salaryCalculate';

import {
    summaryFieldChooser,
    numberFilter,
    orFilter
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';

import { possessColumn, DelayMonth } from '@/pages/SalaryManage/SalaryCalculate/constant/salaryDetailContext';
import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import TablePercentWrapper from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/TablePercentWrapper';

import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';
import ComApplyTable from './ComApplyTable';
import OrganizationNameItem from './OrganizationNameItem';
import style from './index.less';

const {
    getApproveHeadInfo
} = hrOverviewRecheck;


const RecheckSummaryChooser = summaryFieldChooser(
    orFilter(numberFilter, col => ({
        success: col.dataIndex === 'employeeName',
        result: { [col.dataIndex]: '合计' }
    }))
);
const RecheckColumnProcessor = () =>
    new ColumnProcessor(
        { ...possessColumn,
            employeeName: {
                fixed: true,
                width: 135,
                render: (text, record) =>
                    <EmployeeNameWrapper name={text} style={{ width: 100 }} right={record.delayPay ?
                        <DelayMonth yearMonth={record.yearMonth} /> : null} />
            }
        },
        CommonColumnInterceptor,
        null,
        []
    );


const { Item } = Form;

const getWidthMapper = width => {
    let widthMapper;

    // 按一按444（label：130，wrapper: 314）计算
    if (width < 888) {
        widthMapper = { normal: 24, labelCol: 7, wrapperCol: 17 };
    } else if (width < 1332) {
        widthMapper = { normal: 12, labelCol: 7, wrapperCol: 17 };
    } else if (width < 1776) {
        widthMapper = { normal: 8, labelCol: 7, wrapperCol: 17 };
    } else {
        widthMapper = { normal: 6, labelCol: 7, wrapperCol: 17 };
    }

    return widthMapper;
};

const SalaryRecheckApply = ({ form, formValueMap, dataSource, location }) => {
    const [loading, setLoading] = useState(false);
    const [ref, { width }] = useMeasure();
    const widthMapper = getWidthMapper(width);

    const childConfig = dataSource?.children?.length > 0 ? dataSource.children : [];
    const childrenConfigMap = keyBy(childConfig, 'formId');
    const salaryMonthConfig = childrenConfigMap.salaryMonth;
    const organizationNameConfig = childrenConfigMap.organizationName;
    const uploadConfig = childrenConfigMap.OssUploadFiles;
    const prevSalaryMonthRef = useRef();

    const { getFieldDecorator } = form;
    const [pageModel, setPageModel] = useState(formValueMap?.salaryReCheckApplyModel || {});
    const [headerList, setHeaderList] = useState([]);
    const [tableList, setTableList] = useState([]);

    const { contrastType, employeeCode, period, organizationCode, salaryPayrollProcessRecordId } = location.query;
    const isApply = !!contrastType;
    // 由于在申请界面或审批详情界面限定了90%的宽度(表单设计页没有限定)，而且我们要100%，所在增加了负值的marginRight
    const extraRight = isApply || formValueMap;

    const setFieldValue = (filedName, fieldValue) => {
        setPageModel({ ...pageModel, [filedName]: fieldValue });
    };

    // 如果流程附件配置为只读时，后台不会返回配置信息，就无需显示
    if (uploadConfig) {
        uploadConfig.uploadProps.disabled = uploadConfig.options.disabled;
    }

    useEffect(() => {
        if (pageModel.salaryPayrollProcessRecordId) {
            setLoading(true)
            querySalaryPayrollProcessRecordById(pageModel.salaryPayrollProcessRecordId).then(res => {
                setLoading(false)
                if (isSuccess(res)) {
                    const { data } = res
                    const processData = JSON.parse(data || '{}')
                    setHeaderList(processData?.headList)
                    setTableList(processData?.salaryList)
                } else {
                    message.error(res.msg);
                }
            }).catch(e => {
                console.log(e)
                setLoading(false)
            })
        }
    }, [pageModel.salaryPayrollProcessRecordId])

    useMount(async () => {
        if (isApply) {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            try {
                const employeeData = await getApproveHeadInfo({
                    year,
                    month,
                    organizationCode
                })
                if (isSuccess(employeeData)) {
                    setPageModel({
                        year,
                        month,
                        contrastType,
                        organizationCode,
                        ...employeeData.data,
                        salaryPayrollProcessRecordId,
                        approver: employeeCode
                    });
                } else {
                    message.error(employeeData.msg);
                }

                setLoading(false)
            } catch (e) {
                setLoading(false);
            }
        }
    });

    const memoDataSource = useMemo(
        () => [].concat(tableList || []).map(item => ({
            ...item,
            ...item.dynamicSalaryPayrollInfo,
            ...item.dynamicEmployeeInfo
        })),
        [tableList]
    );

    useEffect(
        () => {
            if (formValueMap?.salaryReCheckApplyModel) {
                setPageModel(formValueMap?.salaryReCheckApplyModel);
            }
        },
        [formValueMap]
    );

    useEffect(() => {
        if (prevSalaryMonthRef.current !== pageModel?.salaryMonth && salaryMonthConfig) {
            prevSalaryMonthRef.current = pageModel?.salaryMonth;
            form.setFieldsValue({ [salaryMonthConfig.formId]: pageModel?.salaryMonth });
        }
    }, [form, pageModel, salaryMonthConfig]);

    return (
        <Spin spinning={loading}>
            <div ref={ref} className={classNames(style.salaryReCheckApply, { [style.extraRight]: extraRight })}>
                {getFieldDecorator('salaryReCheckApplyModel', { initialValue: pageModel })(<Input type="hidden" />)}

                {/* 行政机构 */}
                <OrganizationNameItem
                    form={form}
                    formValueMap={formValueMap}
                    organizationNameConfig={organizationNameConfig}
                    organizationCode={pageModel?.organizationCode}
                />

                {/* 备注的薪资月份 */}
                {
                    salaryMonthConfig
                        ? <Form.Item
                            label={salaryMonthConfig.label}
                            key={salaryMonthConfig.formId}
                            style={{ display: salaryMonthConfig?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(salaryMonthConfig?.formId, {
                                rules: salaryMonthConfig?.rules,
                                value: pageModel?.salaryMonth
                            })(<AutoRenderComponent form={form} config={salaryMonthConfig} />)}
                        </Form.Item>
                        : null
                }

                <div>
                    <If condition={pageModel?.organizationCode || formValueMap?.applicationNo }>
                        <Row>
                            <If condition={pageModel?.organizationCode}>
                                <Col span={widthMapper.normal}>
                                    <Form.Item
                                        labelCol={{ span: widthMapper.labelCol }}
                                        wrapperCol={{ span: widthMapper.wrapperCol }}
                                        label="行政机构："
                                        className={classNames(style.mb0)}
                                    >
                                        <OrganizationNameConnect
                                            organizationCode={pageModel?.organizationCode}
                                        />
                                    </Form.Item>
                                </Col>
                            </If>

                            <If condition={formValueMap?.applicationNo}>
                                <Col span={widthMapper.normal}>
                                    <Form.Item
                                        labelCol={{ span: widthMapper.labelCol }}
                                        wrapperCol={{ span: widthMapper.wrapperCol }}
                                        label="申请编号：" className={classNames(style.mb0)}
                                    >
                                        {formValueMap?.applicationNo}
                                    </Form.Item>
                                </Col>
                            </If>
                        </Row>
                    </If>

                    <Row>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="申请人员" className={classNames(style.mb0)}
                            >
                                {pageModel?.applyName}
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="申请日期"
                                className={classNames(style.mb0)}
                            >
                                <DateFormatter value={pageModel?.applyDate} pattern="YYYY-MM-DD" />
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="所在部门"
                                className={classNames(style.mb0)}
                            >
                                {pageModel?.departmentName}
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="本月实发薪资总额"
                                className={classNames(style.mb0)}
                            >
                                {numberFormat(pageModel?.thisMonthEncryptTotalPayAmt, '')}
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="上月实发薪资总额"
                                className={classNames(style.mb0)}
                            >
                                {numberFormat(pageModel?.lastMonthEncryptTotalPayAmt, '')}
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="差异"
                                className={classNames(style.mb0)}
                            >
                                <TablePercentWrapper
                                    rate={pageModel?.encryptTotalPayAmtRrowthRate}
                                    type={
                                        pageModel?.encryptTotalPayAmtRrowthRateFloatingLevel
                                    }
                                />
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="薪资月份"
                                className={classNames(style.mb0)}
                            >
                                {pageModel?.salaryMonth}
                            </Item>
                        </Col>
                        <Col span={widthMapper.normal}>
                            <Item
                                labelCol={{ span: widthMapper.labelCol }}
                                wrapperCol={{ span: widthMapper.wrapperCol }}
                                label="重要提示" className={classNames(style.mb0)}
                            >
                                {!isApply
                                    ? <span className={style.info}><EmptyPlaceHolder value={pageModel.remark} /></span>
                                    : <Input
                                        placeholder="请输入"
                                        maxLength={200}
                                        onChange={e => setFieldValue('remark', e.target.value)}
                                        disabled={!isApply}
                                        title={!isApply ? pageModel.remark : null}
                                        value={pageModel.remark}
                                    />}
                            </Item>
                        </Col>
                    </Row>

                    <ComApplyTable
                        tableLoading={loading}
                        tableHeader={headerList}
                        summaryFields={RecheckSummaryChooser}
                        columnProcessor={RecheckColumnProcessor()}
                        dataSource={memoDataSource}
                    />

                    {uploadConfig ? (
                        <Row>
                            <Form.Item label="附件：" className={classNames(style.mb0, style.flex)}>
                                {getFieldDecorator(uploadConfig?.formId, {
                                    rules: uploadConfig?.rules,
                                    initialValue: formValueMap?.[uploadConfig.formId] ?? uploadConfig.initialValue
                                })(<AutoRenderComponent form={form} config={uploadConfig} />)}
                            </Form.Item>
                        </Row>
                    ) : null}
                </div>
            </div>
        </Spin>
    );
};

export default withRouter(React.memo(SalaryRecheckApply));
